<template>
    <div class="contener">
        <!-- 页面 -->
        <div class="page">
            <!-- 搜索 -->
            <transition
                @before-enter="_beforeEnter"
                @enter="_enter"
                @after-enter="_afterEnter"
                @before-leave="_beforeLeave"
                @leave="_leave"
                @after-leave="_afterLeave"
            >
                <div
                    class="search-contener"
                    ref="searchContener"
                    v-show="searchFormConfig.searchContenerShow"
                >
                    <base-form
                        :formItems="searchFormConfig.formItems"
                        :formData="searchFormConfig.formSubmit"
                        ref="searchForm"
                        @onButtonClick="searchBarButtonClick"
                    />
                </div>
            </transition>
            <!-- 表格 -->
            <div class="datas-contener">
                <!-- 表格操作项 -->
                <div class="option-contener">
                    <data-options
                        :leftConfig="buttonConfig.leftConfig"
                        @buttonClick="handelOptionClick"
                    />
                </div>
                <!-- 表格展示项 -->
                <div class="table-contener">
                    <base-table
                        ref="baseTable"
                        :tableData="baseTableConfig.tableData"
                        :tableHeader="baseTableConfig.tableHeader"
                        :tableConfig="baseTableConfig.tableConfig"
                        @handleSelection="tableDataSelected"
                    >
                        <template slot-scope="{ scope }">
                            <span v-if="scope.type === 'index'">
                                {{ scope.$index + 1 }}
                            </span>

                            <div v-if="scope.type === 'handle'">
                                <el-button
                                    type="text"
                                    icon="el-icon-view"
                                    @click.stop="handlePreview(scope.row)"
                                    v-hasPermi="['tool/gen/preview']"
                                    >预览</el-button
                                >
                                <el-button
                                    type="text"
                                    icon="el-icon-edit"
                                    @click.stop="updateTableData(scope.row)"
                                    v-hasPermi="['tool/gen/editSave']"
                                    >修改</el-button
                                >
                                <el-button
                                    type="text"
                                    icon="el-icon-delete"
                                    @click.stop="deleteTableData(scope.row)"
                                    v-hasPermi="['tool/gen/delete']"
                                    >删除</el-button
                                >
                                <el-button
                                    type="text"
                                    icon="el-icon-refresh"
                                    @click.stop="synchDbHandle(scope.row)"
                                    v-hasPermi="['tool/gen/synchDb']"
                                    >同步</el-button
                                >
                                <!-- 此功能后期再加 -->
                                <!-- <el-button
                                    type="text"
                                    icon="el-icon-download"
                                    @click.stop="genCodeSingle(scope.row)"
                                    >生成代码</el-button
                                > -->
                            </div>
                        </template>
                    </base-table>
                </div>
                <!-- 分页 -->
                <div class="paging-contener">
                    <pagin-ation
                        :size="paginationConfig.size"
                        :total="paginationConfig.total"
                        :type="paginationConfig.type"
                        :currentPage="paginationConfig.currentPage"
                        @PageNumber="pageNumberChange"
                        @PageSize="pageSizeChange"
                    />
                </div>
            </div>
        </div>
        <!-- 弹框 -->
        <el-dialog
            :title="dialogConfig.title"
            :visible.sync="dialogConfig.show"
            :width="dialogConfig.width"
            v-dialogDrag
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            append-to-body
        >
            <!-- 筛选表格列 -->
            <div
                class="dialog-content"
                v-if="dialogConfig.key === 'tableColumn'"
            >
                <base-transfer
                    :transferConfig="tableColumnTransferConfig"
                    ref="baseTransfer"
                />
            </div>
            <!-- 导入按钮 -->
            <div
                class="dialog-content"
                v-if="dialogConfig.key === 'importTableData'"
            >
                <div class="import-contener">
                    <importTable ref="importTable" />
                </div>
            </div>
            <!-- 预览页面 -->
            <div
                class="dialog-content pre-view"
                v-if="dialogConfig.key === 'preView'"
            >
                <el-tabs v-model="preview.activeName">
                    <el-tab-pane
                        v-for="(value, key) in preview.data"
                        :label="
                            key.substring(
                                key.lastIndexOf('/') + 1,
                                key.indexOf('.vm')
                            )
                        "
                        :name="
                            key.substring(
                                key.lastIndexOf('/') + 1,
                                key.indexOf('.vm')
                            )
                        "
                        :key="key"
                        :lazy="true"
                        class="pre-tab-pane"
                    >
                        <el-link
                            :underline="false"
                            icon="el-icon-document-copy"
                            v-clipboard:copy="value"
                            v-clipboard:success="clipboardSuccess"
                            class="copy-span"
                            >复制</el-link
                        >
                        <div class="edit-contener">
                            <monaco-editor
                                :editorOptions="{
                                    value: value,
                                    theme: 'vs-dark',
                                    language: 'java'
                                }"
                            />
                        </div>
                    </el-tab-pane>
                </el-tabs>
            </div>
            <span
                slot="footer"
                class="dialog-footer"
                v-if="
                    dialogConfig.key === 'importTableData' ||
                        dialogConfig.key === 'tableColumn'
                "
            >
                <el-button size="small" type="info" @click="handelCloseDialog"
                    >关 闭</el-button
                >
                <el-button
                    size="small"
                    type="primary"
                    @click="handelCofimeDialog"
                    >确 定</el-button
                >
            </span>
        </el-dialog>
    </div>
</template>
<script>
import BaseForm from '@/components/baseForm/index'
import DataOptions from '@/components/dataOptions/index'
import BaseTable from '@/components/baseTable/index'
import PaginAtion from '@/components/pagination/index'
import BaseTransfer from '@/components/baseTransfer/index'
import globalMixin from '@/mixins/global'
import {
    genList,
    genDel,
    preview,
    genCode,
    batchGenCode,
    synchDb
} from '@/http/apis/tool/gen/index'
import {
    assemblyDataByTableColumn,
    setFormItemProp,
    setSelectFormart
} from '@/utils/tool'
import importTable from './importTable'
import monacoEditor from '@/components/monacoEditor/index'
import { getDataSourceSelectData } from '@/http/apis/system/dataSource/index'

export default {
    mixins: [globalMixin],
    components: {
        BaseForm,
        DataOptions,
        BaseTable,
        PaginAtion,
        importTable,
        monacoEditor,
        BaseTransfer
    },
    data() {
        return {
            dataSourceList: [],
            buttonConfig: {
                leftConfig: [
                    {
                        prop: 'batchGenCodeHandel',
                        label: '下载代码',
                        icon: 'el-icon-download',
                        type: 'primary',
                        disabled: false,
                        hasPermi: ['system/post/save']
                    },
                    {
                        prop: 'importTableData',
                        label: '导入',
                        icon: 'el-icon-upload2',
                        type: 'danger',
                        disabled: false,
                        hasPermi: ['system/post/delete']
                    },
                    {
                        prop: 'deleteTableData',
                        label: '删除',
                        icon: 'el-icon-delete',
                        type: 'info',
                        disabled: false
                    }
                ]
            },
            //编辑器
            editorOptions: {
                value: '',
                theme: 'vs-dark'
            },
            // 搜索表单配置
            searchFormConfig: {
                formItems: [
                    [
                        {
                            ltype: 'select',
                            placeholder: '请选择数据源',
                            label: '数据源',
                            prop: 'datasourceId',
                            width: 'w-auto',
                            options: []
                        },
                        {
                            ltype: 'input', // 大类型（input）
                            placeholder: '请输入表名称', // 文字提示
                            label: '表名称',
                            prop: 'tableName', // 绑定的key
                            width: 'w-auto'
                        },
                        {
                            ltype: 'input', // 大类型（input）
                            placeholder: '请输入表描述', // 文字提示
                            label: '表描述',
                            prop: 'tableComment', // 绑定的key
                            width: 'w-auto'
                        },

                        {
                            ltype: 'button', // 大类型（input）
                            type: 'primary',
                            text: '搜索', // 文字提示
                            prop: 'searchDatas', // 绑定的key
                            icon: 'el-icon-search',
                            width: 'w-auto',
                            loading: false
                        },
                        {
                            ltype: 'button', // 大类型（input）
                            type: 'default',
                            text: '重置', // 文字提示
                            prop: 'resetSearchForm', // 绑定的key
                            icon: 'el-icon-refresh-right',
                            width: 'w-auto'
                        }
                    ]
                ],
                formSubmit: {
                    datasourceId: '0',
                    code: '',
                    name: '',
                    status: ''
                },
                formConfig: {
                    labelPosition: 'right', // label对齐方式
                    labelWidth: 'auto'
                },
                // 搜索控件是否显示
                searchContenerShow: true
            },
            // 表格配置
            baseTableConfig: {
                // 表格数据
                tableData: [],
                // 表格头数据
                tableHeader: [
                    {
                        type: 'selection',
                        width: 50,
                        fixed: 'left',
                        label: '选择',
                        visible: true
                    },
                    {
                        type: 'index',
                        label: '序号',
                        width: 50,
                        visible: true
                    },
                    {
                        prop: 'tableName',
                        label: '表名称',
                        visible: true
                    },
                    {
                        prop: 'tableComment',
                        label: '表描述',
                        visible: true
                    },
                    {
                        prop: 'className',
                        label: '实体',
                        visible: true
                    },
                    {
                        label: '操作',
                        type: 'handle',
                        fixed: 'right',
                        visible: true
                    }
                ],
                // 表格配置
                tableConfig: {
                    loading: false
                },
                // 选中的表格数据
                tableCheckedDatas: []
            },
            // 分页配置
            paginationConfig: {
                type: 'md',
                size: 10,
                currentPage: 1,
                total: 100
            },
            // 弹框配置
            dialogConfig: {
                // 弹框标题
                title: '新增',
                // 是否显示
                show: false,
                // 宽度
                width: '30%',
                // 弹框标识(用来区分弹框内容)
                key: ''
            },
            // 查询表格数据的参数
            queryTableParams: {
                pageNo: 0,
                pageSize: 10,
                entity: {}
            },
            // 表格列筛选配置
            tableColumnTransferConfig: {
                // 穿梭框的数据
                data: [],
                // 穿梭框的标题
                titles: ['显示', '隐藏'],
                // 隐藏的列
                modelList: []
            },
            // 预览参数
            preview: {
                data: {},
                activeName: 'entity.java'
            }
        }
    },
    created() {
        this.initPage()
    },
    methods: {
        /**
         * 页面开始
         */
        async initPage() {
            // 查询数据源列表
            await this.queryDataSourceList()
            //数据源搜索字段设置默认值
            this.setFormsItems()
            //初始化参数
            this.initQueryParmas()

            // 查询岗位列表
            this.queryTableData(this.queryTableParams)
        },
        /**
         * 查询表格数据
         */
        async queryTableData(params) {
            this.baseTableConfig.tableConfig.loading = true
            let res = await genList(params)
            if (res.data) {
                this.baseTableConfig.tableData = res.data.list
                this.paginationConfig.total = res.data.totalCount
            } else {
                this.baseTableConfig.tableData = []
                this.paginationConfig.total = 0
            }
            this.baseTableConfig.tableConfig.loading = false
        },
        /**
         * 数据源列表查询
         */
        async queryDataSourceList() {
            try {
                let res = await getDataSourceSelectData()
                this.dataSourceList = res.data
            } catch (error) {
                this.dataSourceList = []
            }
        },
        /**
         * 设置表单的表单项
         */
        async setFormsItems() {
            // 重新设置新增、修改 表单的部门树数据配置
            let dataSourceSelectData = setSelectFormart(
                this.dataSourceList,
                'datasourceName',
                'datasourceId'
            )
            this.searchFormConfig.formItems = setFormItemProp(
                this.searchFormConfig.formItems,
                'datasourceId',
                'options',
                dataSourceSelectData
            )
        },
        /**
         * 表格数据被选中
         */
        tableDataSelected(rows) {
            this.baseTableConfig.tableCheckedDatas = rows
        },
        /**
         * 初始化查询参数
         */
        initQueryParmas() {
            this.queryTableParams = {
                pageNo: 0,
                pageSize: 10,
                entity: {
                    ...this.searchFormConfig.formSubmit
                }
            }
            this.paginationConfig.size = 10
            this.paginationConfig.currentPage = 1
            this.baseTableConfig.tableData = []
        },

        /**
         * 页码变化
         */
        pageNumberChange(e) {
            this.queryTableParams.pageNo = e
            this.paginationConfig.currentPage = e
            this.queryTableData(this.queryTableParams)
        },
        /**
         * 页大小变化
         */
        pageSizeChange(e) {
            // 页大小变化时，将当前页码设置为0
            this.queryTableParams.pageNo = 0
            // 将当前表格数据设置为空
            this.baseTableConfig.tableData = []
            this.queryTableParams.pageSize = e
            this.queryTableData(this.queryTableParams)
        },

        /**
         * 搜索栏相关
         */
        /**
         * 搜索栏按钮点击
         * @param {Object} params
         */
        searchBarButtonClick(params) {
            // 清空查询参数
            this.initQueryParmas()
            try {
                this[params.prop]()
            } catch (error) {
                throw new Error(error)
            }
        },

        /**
         * 重置搜索表单
         */
        resetSearchForm() {
            // 查询参数初始化
            this.initQueryParmas()
            // 重置搜索表单
            this.$refs.searchForm.resetForm()
            // 查询数据
            this.refreshTableData()
        },

        /**
         * 搜索数据
         */
        searchDatas() {
            this.$refs.searchForm.submitForm(() => {
                // 清空查询参数
                this.initQueryParmas()
                // 组装查询条件
                this.queryTableParams.entity = {
                    ...this.searchFormConfig.formSubmit
                }
                // 查询数据
                this.queryTableData(this.queryTableParams)
            })
        },

        /**
         * 操作栏相关
         */
        /**
         * 操作项点击
         * @param {*} params
         */
        handelOptionClick(params) {
            this[params] ? this[params]() : null
        },

        /**
         * 切换搜索栏的显示状态
         */
        switchSearchStatus() {
            this.searchFormConfig.searchContenerShow = !this.searchFormConfig
                .searchContenerShow
        },

        /**
         * 刷新表格数据
         */
        refreshTableData() {
            // 将当前表格数据设置为空
            this.baseTableConfig.tableData = []
            this.queryTableData(this.queryTableParams)
        },

        /**
         * 设置表格显示隐藏列(打开弹框)
         */
        switchTableColumn() {
            let dialogParams = {
                title: '显示/隐藏',
                width: 'auto',
                show: true,
                key: 'tableColumn'
            }
            // 设置参与表格列控制的属性（最后的数组为不参与隐藏显示设置的列）
            this.tableColumnTransferConfig.data = assemblyDataByTableColumn(
                this.baseTableConfig.tableHeader,
                'label',
                ['选择', '表名称', '操作']
            )
            this.handelOpenDialog(dialogParams)
        },
        /**
         * 设置表格显示隐藏列(弹框确认)
         */
        switchTableColumnButtonClick() {
            let newData = this.$refs.baseTransfer.backCheckedData()
            if (newData && newData.length > 0) {
                this.baseTableConfig.tableHeader.forEach(ele => {
                    ele.visible = !newData.includes(ele.label)
                })
            } else {
                this.baseTableConfig.tableHeader.forEach(ele => {
                    ele.visible = true
                })
            }
            this.handelCloseDialog()
        },

        /**
         * 导入数据
         */
        importTableData() {
            let dialogParams = {
                title: '导入表',
                width: '60%',
                show: true,
                key: 'importTableData'
            }
            this.handelOpenDialog(dialogParams)
        },

        /**
         * 修改表格数据
         */
        updateTableData(row) {
            console.log('ow.tableId', row.tableId)
            this.$router.push({
                name: 'EditForm',
                params: {
                    tableId: row.tableId
                }
            })
        },

        /**
         * 删除表格数据
         */
        deleteTableData(rows) {
            if (
                typeof rows === 'undefined' &&
                this.baseTableConfig.tableCheckedDatas.length > 0
            ) {
                rows = this.baseTableConfig.tableCheckedDatas
            }

            if (typeof rows !== 'undefined') {
                let data = []
                if (Array.isArray(rows) && rows.length) {
                    for (let i = 0; i < rows.length; i++) {
                        const element = rows[i]
                        data.push(element.tableId)
                    }
                } else {
                    data = [rows.tableId]
                }
                this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(async () => {
                        let res = await genDel(data)
                        if (res && res.code == 0) {
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            })
                        } else {
                            this.$message({
                                type: 'error',
                                message: '删除失败!'
                            })
                        }
                        // 查询数据
                        this.refreshTableData()
                    })
                    .catch(() => {
                        this.$message({
                            type: 'info',
                            message: '已取消删除'
                        })
                    })
            } else {
                this.$message({
                    type: 'error',
                    message: '请选择数据！'
                })
            }
        },

        /**
         * 预览界面
         */
        async handlePreview(rows) {
            let parasm = {
                tableId: rows.tableId
            }
            let assRes = await preview(parasm)
            if (assRes && assRes.code === 0) {
                this.preview.data = assRes.data
                this.preview.open = true
                this.preview.activeName = 'entity.java'
            }
            // // 打开新增弹框
            let dialogParams = {
                title: '代码预览',
                width: '70%',
                show: true,
                key: 'preView'
            }
            this.handelOpenDialog(dialogParams)
        },

        /**
         * 复制代码成功
         */
        clipboardSuccess() {
            this.$modal.msgSuccess('复制成功')
        },

        /**
         * 弹框相关
         */

        /**
         * 打开弹框
         * @param {*} params
         */
        handelOpenDialog(params) {
            this.dialogConfig = params
        },
        /**
         * 初始化弹框
         */
        handelInitDialog() {
            this.dialogConfig = {
                title: '',
                show: false,
                width: '',
                key: ''
            }
        },
        /**
         * 关闭弹框
         */
        handelCloseDialog() {
            this.handelInitDialog()
        },
        /**
         * 弹框确定
         */
        handelCofimeDialog() {
            // 表格列筛选的弹框
            if (this.dialogConfig.key === 'tableColumn') {
                this.switchTableColumnButtonClick()
            } else if (this.dialogConfig.key === 'importTableData') {
                this.$refs.importTable.handelCofimeDialog()
            }
        },
        /**
         * 行上的生成代码
         */
        genCodeSingle(rows) {
            let params = {
                tableName: rows.tableName
            }
            let assRes = genCode(params)
            if (assRes && assRes.code === 0) {
                alert('生成代码成功！')
            }
        },
        /**
         * 批量生成代码-下载代码
         */
        batchGenCodeHandel() {
            let rows = this.baseTableConfig.tableCheckedDatas
            if (rows == '') {
                this.$modal.msgError('请选择要生成的数据')
                return
            }
            let data = []
            if (Array.isArray(rows) && rows.length) {
                for (let i = 0; i < rows.length; i++) {
                    const element = rows[i]
                    data.push(element.tableName)
                }
            } else {
                data = [rows.tableName]
            }
            batchGenCode(data, 'dafang.zip')
        },
        /**
         * 表结构同步
         */
        async synchDbHandle(row) {
            let parasm = {
                tableName: row.tableName,
                dataSourceId: row.datasourceId
            }
            let assRes = await synchDb(parasm)
            if (assRes && assRes.code === 0) {
                this.$message.success({ message: '同步成功！' })
            } else {
                this.$message.error({ message: '同步失败！' })
            }
        }
    }
}
</script>
<style lang="scss" scoped>
.dialog-content {
    width: 100%;
    height: 60vh;
    .import-contener {
        width: 100%;
        height: 100%;
    }
}
.pre-view {
    padding-bottom: $margin-md;
    .pre-tab-pane {
        @include box_flex(
            $width: 100%,
            $height: 100%,
            $direction: column,
            $justify: flex-start,
            $align: flex-start
        );
        @include box_flex(
            $width: 100%,
            $height: 100%,
            $direction: column,
            $justify: flex-start,
            $align: flex-start
        );
        .copy-span {
            padding-bottom: 10px;
        }
        .edit-contener {
            width: 100%;
            height: 50vh;
        }
    }
}
</style>
